<template>
	<up-navbar title="添加成员" placeholder @leftClick="close"></up-navbar>
	<!-- 搜索 -->
	<view style="margin:  0 24rpx; background-color: #fff;">
		<up-search @search="reloadList" @clear="reloadList" :showAction="false" clearabled placeholder="搜索" v-model="keyword" shape="square"></up-search>
	</view>
	<view class="list-box">
		<!-- 列表 -->
		<up-list height="77vh">
			<mescroll-uni ref="mescrollRef" :top="listHeightStyle.top" bottom="120rpx" @init="mescrollInit" @down="downCallback" @up="upCallback" :up="upOption">
				<up-list-item v-for="item in filteredMessages" :key="item.id" style="padding: 0 20rpx;">
					<view class="list-item" @click="removeAndAdd(item)">
						<view class="check">
							<up-checkbox usedAlone :checked="setChecked(item)" @change="removeAndAdd(item)"></up-checkbox>
						</view>
						<view v-show="item.isGroup == 0" class="img" style="width: 83rpx; height: 83rpx;">
							<up-image :src="setUserImg(item)" width="100%" height="100%" radius="10rpx">
								<template #error>
									<text>{{showUserName(item.username)}}</text>
								</template>
							</up-image>
						</view>
						<view v-show="item.isGroup == 1" class="img" style="width: 83rpx; height: 83rpx;">
							<group-avatar :chat="item" :groupname="item.group_name"></group-avatar>
						</view>
						<view>
							{{item.isGroup == 1 ? item.group_name : item.username}}
						</view>
					</view>
				</up-list-item>
			</mescroll-uni>
		</up-list>
	</view>

	<!-- 底部选中 -->
	<view class="select-container">
		<view class="select-left">
			<text>已选择（{{selection?.length}}）:</text>
		</view>
		<scroll-view class="scrollContainer" scroll-x>
			<view style="display: flex; width: 100%;" @click="selectedShow = true">
				<view v-for="item in selection" :key="item.id" class="select-item">
					<up-image v-show="item.isGroup == 0" :src="setUserImg(item)" width="100%" height="100%" radius="10rpx">
						<template #error>
							<text>{{showUserName(item.username)}}</text>
						</template>
					</up-image>
					<view v-show="item.isGroup == 1" class="img" style="width: 100%; height: 100%;">
						<group-avatar :chat="item" :groupname="item.group_name"></group-avatar>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="select-right">
			<up-button @click="submit" :customStyle="{border: 'none', width: '102rpx', height: '52rpx'}" :disabled="selection?.length == 0" type="primary" text="确定"></up-button>
		</view>
	</view>

	<!-- 移除弹出框 -->
	<up-popup :show="selectedShow" @close="selectedShow = fasle">
		<view class="popup-header">
			<view @click="selectedShow = false">
				<up-icon :size="18" bold name="close"></up-icon>
			</view>
			<view style="font-weight: 500;">已选择({{selection?.length}})</view>
			<view @click="selectedShow = false"></view>
		</view>
		<view class="popup-content">
			<up-list height="600rpx">
				<up-list-item v-for="item in selection" :key="item.id" style="padding: 0 20rpx;">
					<view class="list-item" @click="removeAndAdd(item)">
<!-- 						<view class="check">
							<up-checkbox usedAlone :checked="setChecked(item)"></up-checkbox>
						</view> -->
						<view v-show="item.isGroup == 0" class="img" style="width: 64rpx; height: 64rpx;">
							<up-image :src="setUserImg(item)" width="100%" height="100%" radius="10rpx">
								<template #error>
									<text>{{showUserName(item.username)}}</text>
								</template>
							</up-image>
						</view>
						<view v-show="item.isGroup == 1" class="img" style="width: 64rpx; height: 64rpx;">
							<group-avatar :chat="item" :groupname="item.group_name"></group-avatar>
						</view>
						<view>
							{{item.isGroup == 1 ? item.group_name : item.username}}
						</view>
						<view class="del">
							<up-button type="primary" size="mini" :hairline="false" @click="removeAndAdd(item)" text="移除"></up-button>
						</view>
					</view>
				</up-list-item>
			</up-list>
		</view>
	</up-popup>
</template>

<script>
import { getCurrentInstance } from "vue";
import { chatApi } from '@/apis/cloud/chat'
import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
import { useUserStore } from '@/pinia-store/user'
import GroupAvatar from './GroupAvatar.vue'


const AvaterBaseUrl = "https://cloud.mfarmers.com/dist/interface/public/upload/avatar/";

export default {
  name: "GroupMemberPicker",
	components: {
		GroupAvatar
	},
	mixins: [MescrollMixin],
	data() {
		return {
			upOption: {
				page: {
					size: 20 // 每页数据的数量,默认10
				},
				noMoreSize: 5, // 配置列表的总数量要大于等于5条才显示'-- END --'的提示
				empty: {
					tip: '已经到底了'
				}
			},
			show: false,
			selectedShow: false,
			currentData: [],
			selection: [],
			chatList: [],
			pageSize: 20,
			pageNum: 1,
			total: 0,
			keyword: '',
      userInfo: {},
      source:'',
      listHeight: 0, // 动态计算的高度
      listHeightStyle: {}, // 动态计算的样式
      topHeight: 0,
      andaddpersonnel:null
		};
	},
  created(){
    this.calculateListHeight()
  },
	onLoad(options) {
		const userStore = useUserStore();
		this.userInfo = userStore.user;
		const eventChannel = this.getOpenerEventChannel();
		eventChannel.on('setSelectChat', (data) => {
			this.selection = JSON.parse(data.data);
		});
	},
	computed: {
		filteredMessages() {
			const cache = this.chatList.filter(item => {
				if(item.isGroup == 1) {
					return item?.group_name.indexOf(this.keyword) != -1
				}else {
					return item.username.indexOf(this.keyword) != -1
				}
			});
			if(this.keyword == '') {
				return this.chatList
			}else {
				return cache
			}
		},
	},
	methods: {
    calculateListHeight() {
      // #ifdef APP-PLUS
      this.listHeightStyle = {
        top:'220rpx'
      };
      // #endif

      // #ifdef H5
      this.listHeightStyle = {
        top:'155rpx'
      };
      // #endif
    },
		mescrollInit(mescroll) {
			this.mescroll = mescroll;
		},
		/*上拉加载的回调*/
		upCallback(page) {
			this.pageNum = page.num; // 页码, 默认从1开始
			this.pageSize = page.size; // 页码, 默认从1开始
			this.getList();
		},
		/*若希望重新加载列表,只需调用此方法即可(内部会自动page.num=1,再主动触发up.callback)*/
		reloadList(){
			this.chatList = [];
			this.mescroll.resetUpScroll();
		},
		close() {
      uni.navigateBack();
		},
		submit() {
      uni.navigateBack();
			uni.$emit('selectChatGroup',JSON.stringify(this.selection))
		},
		setUserImg(item) {
			return AvaterBaseUrl+item.friend_phone+'.jpg'
		},
		// 名称超长处理
		showUserName(username) {
			if (username && username.length > 2) {
				return username.substr(1, 2);
			} else {
				return username;
			}
		},
		// 是否选中
		setChecked(event) {
			const findIndex = this.selection?.findIndex(i => {
				if(event.isGroup == 1) {
					return event.group_id == i.group_id
				}else {
					return event.dialog_id == i.dialog_id
				}
			});
			if(findIndex != -1) {
				return true
			}else {
				return false
			}
		},
		// 移除
		removeAndAdd(item) {
      const findIndex = this.selection?.findIndex(i => {
				if(item.isGroup == 1) {
					return item.group_id == i.group_id
				}else {
					return item.dialog_id == i.dialog_id
				}
			});
      if (findIndex != -1) {
        this.selection.splice(findIndex, 1);
      } else {
        this.selection.push(item);
      }
		},
		back() {
			uni.navigateBack();
		},
		// 用户列表
		async getList() {
      let token = uni.getStorageSync('token')
			const params = {
				'data[account]': this.userInfo.chat_account,
				'data[token]': this.userInfo.token,
				'data[myAccount]': this.userInfo.chat_account,
				// url: 'index.php/users/Index/getMyTree',
				url: 'index.php/users/Index/getChatListCached'
			}
			
			const msg = await chatApi(this?.userInfo?.token || token, params)
			
			if (msg.code == 200) {
				this.chatList = msg.data.friends;
				this.mescroll.endByPage(msg.data.friends.length, 0);
			}else {
				this.mescroll.endErr()
			}
		},
	}
};
</script>

<style lang="scss" scoped>
.list-item {
	position: relative;
	display: flex;
	align-items: center;
	padding: 20rpx;
	border-bottom: 1px solid rgba(0, 0, 0, .1);
	.check {
		margin-right: 10rpx;
	}
	.img {
		margin-right: 24rpx;
		text {
			display: inline-block;
			width: 100%;
			height: 100;
			border-radius: 10rpx;
			color: #fff;
			font-size: 26rpx;
			text-align: center;
			line-height: 83rpx;
			background-color: #3D85FC;
		}
	}
	.del {
		position: absolute;
		right: 10rpx;
		top: 50%;
		transform: translateY(-50%);
	}
}
.select-container {
	position: fixed;
	box-sizing: border-box;
	bottom: 0;
	padding: 20rpx 20rpx 40rpx 20rpx;
	width: 100vw;
	display: flex;
	align-items: center;
	background-color: #fff;
	border-top: 1px solid #E1E3E5;
	.scrollContainer {
		width: 57%;
	}
	.select-left {
		font-size: 26rpx;
		width: 25%;
	}
	.select-right {
		flex: 1;
	}
}

.select-item {
	width: 60rpx;
	height: 60rpx;
	margin-right: 6rpx;
	flex-shrink: 0;
	text {
		display: inline-block;
		width: 100%;
		height: 100;
		border-radius: 10rpx;
		color: #fff;
		font-size: 20rpx;
		text-align: center;
		line-height: 60rpx;
		background-color: #3D85FC;
	}
}
.popup-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	font-size: 32rpx;
	padding: 30rpx;
}
.popup-content {

}
</style>
